package com.kzw.config.inteceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.kzw.contants.ExceptionEnum;
import com.kzw.contants.JwtConstants;
import com.kzw.core.bean.Msg;
import com.kzw.misc.utils.JwtUtil;
import com.kzw.misc.utils.ToolUtil;

import io.jsonwebtoken.JwtException;

/**
 * api接口拦截器
 */
public class RestApiInteceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		return check(request, response);
	}

	private boolean check(HttpServletRequest request, HttpServletResponse response) {
		if (request.getServletPath().equals(JwtConstants.AUTH_PATH)) {
			return true;
		}
		final String token = request.getHeader(JwtConstants.AUTH_HEADER);
		if(StringUtils.isBlank(token)) {
			// 有异常就是token解析失败
			ToolUtil.renderJson(response, Msg.error("token校验失败"));
			return false;
		}
		
		// 验证token是否过期,包含了验证jwt是否正确
		try {
			boolean flag = JwtUtil.isTokenExpired(token);
			if (flag) {
				ToolUtil.renderJson(response, Msg.error(ExceptionEnum.TOKEN_EXPIRED.getMessage()));
				return false;
			}
		} catch (JwtException e) {
			// 有异常就是token解析失败
			ToolUtil.renderJson(response, Msg.error("token校验失败"));
			return false;
		}
		
		// 获得登陆用户
//		WxUser wxUser = JwtUtil.getCurrentUser(token);
//		request.setAttribute("user", wxUser);
		
		return true;
	}
}
